package com.qf.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;


@CrossOrigin("*")
@RestController
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @RequestMapping("/list")
    public Object list(String key, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "add_time") String sort,
                       @RequestParam(defaultValue = "desc") String order){

        //1.查询并返回分页对象
        IPage<DtsStorage> resultPage = storageService.queryStoragePage(key, name, page, limit, sort, order);
        //获取结果集
        List<DtsStorage> list = resultPage.getRecords();

        //获取查询总条数
        long total = resultPage.getTotal();

        //封装对象返回
        HashMap<String, Object> data = new HashMap<>();
        data.put("total",total);
        data.put("items",list);

        return ResponseUtil.ok(data);

    }

    @RequestMapping("/create")
    public Object add(@RequestParam("file") MultipartFile file) throws  Exception{
        //1.获取文件名
        String filename=file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)){
            throw new RuntimeException("上传的文件为空，不允许上传！！");
        }
        //2.获取文件扩展名
        String ext = filename.substring(filename.lastIndexOf("."));
        //3.获取文件大小
        long size = file.getSize();
        //获取文件内容
        byte[] content = file.getBytes();
        //上传并返回上传保存后的文件对象
        DtsStorage storage = storageService.add(filename, (int) size, ext, content);
        //封装数据返回
        return ResponseUtil.ok(storage);

    }
    @RequestMapping("/update")
    public Object update(@RequestBody DtsStorage storage){
        int count = storageService.update(storage);
        if (count==0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }
    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsStorage storage){
        String key = storage.getKey();

        if (StringUtils.isEmpty(key)){
            return ResponseUtil.badArgument();
        }
        storageService.deleteByKey(key);

        return ResponseUtil.ok();

    }
}
